<template>
    <div class="level-list-container">
        <!-- 页面头部 -->
        <div class="add-section">
            <el-button type="primary" :icon="CirclePlusFilled" @click="handleAddLevel">新增等级</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="levelName" label="等级名称" />
                    <el-table-column prop="levelCode" label="等级代码" width="120" align="center" />
                    <el-table-column prop="memberLevel" label="会员等级" width="100" align="center" />
                    <el-table-column prop="growthValue" label="成长值" width="100" align="center" />
                    <el-table-column prop="consumptionAmount" label="消费金额" width="120" align="center">
                        <template #default="{ row }">
                            {{ row.consumptionAmountDesc || `${row.consumptionAmount}元` }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
                    <el-table-column prop="status" label="状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getStatusType(row.status)">
                                {{ getStatusText(row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatDateTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        总共{{ pagination.total }}条记录,当前在第{{ pagination.currentPage }}页
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.currentPage"
                        v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="pagination.total"
                        layout="sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handlePageChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { formatTime } from '@/utils/time';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { MemberLevel, MemberLevelQueryParams } from '@/types/memberLevel'
import { getMemberLevelPage, deleteMemberLevel } from '@/api/member/member-level'
import { CirclePlusFilled } from '@element-plus/icons-vue'

const router = useRouter()

// 表格数据
const loading = ref(false)
const tableData = ref<MemberLevel[]>([])

// 分页数据
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 获取会员等级列表数据
const getData = async () => {
    loading.value = true
    try {
        const params: MemberLevelQueryParams = {
            current: pagination.currentPage,
            size: pagination.pageSize,
            language: 'zh-CN'
        }
        
        console.log('请求参数:', params)
        
        const res = await getMemberLevelPage(params)
        console.log('API响应:', res)
        
        const responseData = res as any
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || []
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0
            
            if (tableData.value.length === 0) {
                ElMessage.info('暂无会员等级数据')
            }
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取会员等级数据失败'
            ElMessage.error(errorMsg)
            tableData.value = []
            pagination.total = 0
        }
    } catch (error) {
        console.error('获取会员等级数据失败:', error)
        ElMessage.error('网络错误，请稍后重试')
        tableData.value = []
        pagination.total = 0
    } finally {
        loading.value = false
    }
}

// 状态文本
const getStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '禁用',
        1: '启用'
    }
    return statusMap[status] || '未知'
}

// 状态类型
const getStatusType = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: 'danger',
        1: 'success'
    }
    return statusMap[status] || 'info'
}

// 时间格式化
const formatDateTime = (dateStr: string) => {
    if (!dateStr) return '-'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '/')
}

// 新增等级
const handleAddLevel = () => {
    router.push('/level-form')
}

// 编辑等级
const handleEdit = (row: any) => {
    router.push(`/level-form/${row.id || '1'}`)
}

// 删除等级
const handleDelete = async (row: MemberLevel) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除等级"${row.levelName}"吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        
        loading.value = true
        const res = await deleteMemberLevel(row.id)
        const responseData = res as any
        
        if (responseData && responseData.code === 200) {
            ElMessage.success('删除成功')
            getData() // 刷新列表
        } else {
            const errorMsg = (responseData && responseData.msg) || '删除失败'
            ElMessage.error(errorMsg)
        }
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除会员等级失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    } finally {
        loading.value = false
    }
}

// 分页处理
const handlePageChange = (page: number) => {
    pagination.currentPage = page
    getData()
}

const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    getData()
}

onMounted(() => {
    getData()
})
</script>

<style scoped>
.level-list-container {
    padding: 20px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

/* 新增按钮区域 */
.add-section {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    gap: 12px;
}

.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
}

.pagination-info {
    font-size: 14px;
    color: #606266;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__body) {
    padding: 20px;
}

:deep(.el-table) {
    border-radius: 4px;
}

:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-form-item) {
    margin-bottom: 16px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-button) {
    border-radius: 4px;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 4px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
    border-radius: 4px;
}
</style>
